﻿using System.Web.Mvc;
using Kym.Core;
using Kym.Web.Views.Messages;
using MvcContrib;
using MvcContrib.Attributes;
using NHibernate.Criterion;
using ProjectBase.Core;
using Rhino.Commons;

namespace Kym.Web.Controllers
{
    public class MessagesController : ConventionController
    {
        private readonly IRepository<Message> messageRepository;
        private readonly IRepository<Contact> contactRepository;

        public MessagesController(IRepository<Message> messageRepository, IRepository<Contact> contactRepository)
        {
            Check.Require(contactRepository != null, "contact repository should not be null");
            Check.Require(messageRepository != null, "message repository should not be null");

            this.messageRepository = messageRepository;
            this.contactRepository = contactRepository;
        }

        public ActionResult List()
        {
            var messages = messageRepository.FindAll(0, 10, Order.Desc("DeliveryDate"));

            return View(messages);
        }

        public ActionResult Details(int id)
        {
            Check.Require(id != 0, "id must be grater than 0");

            var message = messageRepository.Get(id);

            return View(message);
        }

        public ActionResult New()
        {
            return RedirectToAction<MessagesController>(c => c.Edit(null));
        }

        public ActionResult Edit(int? id)
        {
            var message = id.HasValue ? messageRepository.Get(id) : null;
            var contacts = contactRepository.FindAll();

            return View(new MessageEditViewData {Contacts = contacts, Message = message});
        }

        [Transaction]
        public ActionResult CreateOrUpdate([Deserialize("Message")] Message message)
        {
            Check.Require(message != null, "message should not be null");

            messageRepository.SaveOrUpdate(message);

            return RedirectToAction<MessagesController>(c => c.List());
        }

        [Transaction]
        public ActionResult Delete(int id)
        {
            Check.Require(id > 0, "id must be greater than 0, repository cannot delete a transient object");

            var message = messageRepository.Get(id);

            Check.Assert(message != null);

            messageRepository.Delete(message);

            return RedirectToAction<MessagesController>(c => c.List());
        }
    }
}